/*
 * Copyright © 2011 by Rob Cash
 * 
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * 
 * JAXBRegistryInspector.java
 * 
 * Created on Jul 31, 2011 at 1:09:08 PM
 */
package org.robcash.commons.plugin.impl.registry;

import java.net.URL;
import java.util.Collections;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.robcash.commons.plugin.PlugInManagerException;
import org.robcash.commons.plugin.RegistryInspector;
import org.robcash.xmlns.commons.plugin.registry.PlugInInfoType;
import org.robcash.xmlns.commons.plugin.registry.PlugInRegistryType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JAXB based RegistryInspector
 * @author Rob Cash
 */
public class JAXBRegistryInspector implements RegistryInspector<PlugInInfoType>
{
	private String jaxbContextPath = "org.robcash.xmlns.commons.plugin.registry";

	private static final Logger LOG = LoggerFactory.getLogger(JAXBRegistryInspector.class);

	public void setJaxbContextPath(final String path)
	{
		jaxbContextPath = path;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<PlugInInfoType> getPlugInInfoFromRegistry(final URL registryURL)
			throws PlugInManagerException
			{
		try
		{
			JAXBContext jaxbContext = JAXBContext.newInstance(jaxbContextPath);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			Object registry =
					unmarshaller.unmarshal(registryURL);
			if ( registry instanceof PlugInRegistryType )
			{
				return ((PlugInRegistryType) registry).getPlugInInfo();
			}
			else if ( registry instanceof JAXBElement<?> &&
					((JAXBElement<?>) registry).getDeclaredType().equals(PlugInRegistryType.class) )
			{
				return ((JAXBElement<PlugInRegistryType>) registry).getValue().getPlugInInfo();
			}
			return Collections.emptyList();
		}
		catch( JAXBException je )
		{
			LOG.error("Discovery failed", je);
			throw new PlugInManagerException("Discovery failed", je);
		}
			}

}
